﻿//创建人:zxx
/*数据绑定*/
var getUrl = "http://" + this.location.host;
/*数据绑定*/
function BindData() {
    YAHOO.example.XHR_JSON = function () {
        /*定义数据*/
        var myColumnDefs = const_DataFields;
        /*定义数据请求*/
        if (requireUrl == "") {
            requireUrl = "../../Extend/AjaxData/JSONList.aspx?";
        }
        var myDataSource = new YAHOO.util.DataSource(requireUrl);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.connXhrMode = "queueRequests";
        /*定义数据源的请求结构*/
        myDataSource.responseSchema = {
            resultsList: "rows",
            metaFields: { totalRecords: "total" },
            fields: const_DataColums
        };

        this.myDataTable = new YAHOO.widget.DataTable("json", myColumnDefs,
                    myDataSource,
                    { initialRequest: initialRequestUrl
                    , selectionMode: "single"
                    });

        mDataTable = this.myDataTable;
        var mySuccessHandler = function () {
            this.set("sortedBy", null);
            this.onDataReturnAppendRows.apply(this, arguments);
        };

        var myFailureHandler = function () {
            //this.showTableMessage(YAHOO.widget.DataTable.MSG_ERROR, YAHOO.widget.DataTable.CLASS_ERROR);
            this.showTableMessage("没有数据", "没有数据");
            this.onDataReturnAppendRows.apply(this, arguments);
        };

        // 定义回传方法
        var callbackObj = {
            success: mySuccessHandler,
            failure: myFailureHandler,
            scope: myDataTable
        };


        // 调用自定义双击行的方法
        var onRowDoubleClick = function () {
            if (typeof (CustomDbClick) == "function") {
                CustomDbClick();
            } else {
                if (typeof (fnView) == "function") {
                    fnView("e");
                }
            }
        };

        var onCellClick = function (e) {
            //            var ctrl = event.srcElement||e;
            //            if (ctrl.nodeName == "DIV") {
            //                if (ctrl != _o) {
            //                    var o = document.getElementById("tx");
            //                    if (o != undefined) {
            //                        _o.innerHTML = document.getElementById("tx").value;
            //                    }
            //                }
            //                _o = ctrl;
            //                var ctrl2 = "<input id='tx' width='100%' onblur='ontest(this)' value='" + ctrl.innerHTML + "'>";
            //                ctrl.innerHTML = ctrl2;
            //                var o = document.getElementById("tx");
            //                o.focus();
            //                //alert(ctrl.innerHTML);
            //            }
        }

        // 注册相关方法给相关事件
        this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
        this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
        this.myDataTable.subscribe("rowClickEvent", this.myDataTable.onEventSelectRow);
        this.myDataTable.subscribe("cellClickEvent", this.myDataTable.onEventShowCellEditor);
        this.myDataTable.subscribe("cellClickEvent", onCellClick);
        this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
        this.myDataTable.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });

        // Programmatically select the first row 
        this.myDataTable.selectRow(this.myDataTable.getTrEl(0));
        hideCol();
        fnCreateChkAllCheckBox();

        //fnFixTableHeader();
    } ();
}
//隐藏ID列
function hideCol() { mDataTable.hideColumn(parseInt(0)); mDataTable.refreshView(); };
//创建复选框
var fnCreateChkAllCheckBox = function () {
    if ((document.getElementById("chkAll")) == null) {
        var e1 = window.document.getElementById("yui-dt16-th-iSun_Selected");
        if (e1 == null) {
            e1 = window.document.getElementById("yui-dt27-th-iSun_Selected");
        }
        if (e1 == null) {
            return;
        }
        if (typeof (e1) != "undefined") {
            var in1 = e1.firstChild;
            var el = document.createElement("input");
            el.setAttribute("type", "checkbox");
            el.setAttribute("id", "chkAll");
            el.setAttribute("onclick", "fnChkAll()");
            el.setAttribute("style", "margin-left:0px;margin-top:0px;z-index:200")
            in1.insertBefore(el);
        }
    }
}
//全选
var fnChkAll = function () {
    //debugger;
    var ck = document.getElementsByTagName("input");
    for (var i = 0; i < ck.length; i++) {
        if (ck[i].getAttribute("type") == "checkbox" & ck[i].id != "checkAndOr") {
            ck[i].checked = document.getElementById("chkAll").checked;
            if (mDataTable._oRecordSet._records[i] != undefined) {
                mDataTable._oRecordSet._records[i]._oData.iSun_Selected = ck[i].checked;
            }
        }
    }
}
function RefreshData() {
    //initialRequestUrl = "pageindex=1&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + decodeURI(const_CustomCondition);
    BindData();
    ReLoadData();
}
function ReloadData() {
    $('#tt').datagrid({
        url: getUrl+'/Extend/AjaxData/JSONList.aspx?n=' + Math.random()
    });
}

//----------------------------------
//数据删除操作
//----------------------------------
var fnDelete = function (deleteEntity) {
    if (typeof (fnCustomDelete) == "function") {
        fnCustomDelete();
        return;
    } else {
        var list = this.mDataTable.getRecordSet()._records;
        var elist = [];
        dl = [];
        for (var i = 0; i < list.length; i++) {
            //this.getRecordSet()._records[0]._oData["BarItem"]
            if (list[i]._oData["iSun_Selected"] == true) {
                elist.push(list[i]._oData[const_entityID]);
                dl.push(list[i]._sId); //获取行ID；
            }
        }
        if (elist.length == 0) {
            var recordID = myDataTable.getSelectedRows()[0];
            record = myDataTable.getRecord(recordID);
            SaveUrl = getUrl + "/Extend/AjaxData/DataSave.aspx?r=" + Math.random() + "&action=delete&entity=" + deleteEntity + "&id=" + record.getData(const_entityID);
        }
        else {
            SaveUrl = getUrl + "/Extend/AjaxData/DataSave.aspx?r=" + Math.random() + "&action=delete&entity=" + deleteEntity + "&json=" + elist.join(",");
        }
        YAHOO.example.container.dialog3.show();
        //DeleteData("AjaxData/DataSave.aspx?r=" + Math.random()+"&action=delete&entity="+const_EditEntity+"&id="+record.getData(const_entityID),LoadData);           
    }
}

//删除
function DeleteData() {
    if (typeof (fnCustomDeleteData) == "function") {
        fnCustomDeleteData();
        return;
    } else {

        YAHOO.util.Connect.asyncRequest('POST', SaveUrl, {
            success: function (res) {
                try {
                    var str = res.responseText;

                    if (str == "1") {
                        alert("数据删除成功");
                        var recordID = mDataTable.getSelectedRows()[0];
                        if (dl.length == 0) {
                            mDataTable.deleteRow(recordID);
                        }
                        else {
                            for (var i = 0; i < dl.length; i++) {
                                mDataTable.deleteRow(dl[i]);
                            }
                        }
                    }
                    else {
                        alert(str + "\n" + "数据删除失败!");
                    }
                }
                catch (e) {
                }
                finally {
                }
            },
            failure: function (error) {
                alert("数据错误：" + error.statusText);
            }
        }, null);
        YAHOO.example.container.dialog3.hide();
    }
}
